import json
import time
import hashlib
from pathlib import Path

class AnalysisCache:
    def __init__(self, cache_file="analysis_cache.json", expiration=24*60*60):
        self.cache_file = Path(cache_file)
        self.expiration = expiration
        self.cache = self.load_cache()
        
    def load_cache(self):
        """加载缓存"""
        if self.cache_file.exists():
            try:
                with open(self.cache_file, 'r', encoding='utf-8') as f:
                    return json.load(f)
            except:
                return {}
        return {}
    
    def save_cache(self):
        """保存缓存"""
        with open(self.cache_file, 'w', encoding='utf-8') as f:
            json.dump(self.cache, f, ensure_ascii=False, indent=2)
    
    def get_cache_key(self, text: str, prompt: str) -> str:
        """生成缓存键"""
        content = f"{text}:{prompt}"
        return hashlib.md5(content.encode('utf-8')).hexdigest()
    
    def get(self, text: str, prompt: str) -> str:
        """获取缓存的分析结果"""
        key = self.get_cache_key(text, prompt)
        if key in self.cache:
            cache_data = self.cache[key]
            # 检查是否过期
            if time.time() - cache_data['timestamp'] < self.expiration:
                return cache_data['result']
            else:
                del self.cache[key]
                self.save_cache()
        return None
    
    def set(self, text: str, prompt: str, result: str):
        """设置缓存"""
        key = self.get_cache_key(text, prompt)
        self.cache[key] = {
            'timestamp': time.time(),
            'result': result
        }
        self.save_cache() 